# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from odoo import fields, _, models, api
from odoo.exceptions import ValidationError

from . import utils


class TourSaleOrder(models.Model):
    """包车订单"""
    _name = "tour.sale.order"
    _inherit = 'sale.order'
    _table = 'sale_order'
    _description = u'订单'

    owner_id = fields.Many2one('tour.owner', string=u"车主", required=True)
    partner_id = fields.Many2one('tour.travel.agency', string=u'用户', required=True)
    state = fields.Selection([('draft', u'已下单'),
                              ('cancel', u'已取消'),
                              ('sale', u'已确认'),
                              ('paid', u'已支付'),
                              ('pay error', u'支付失败'),
                              ('stop', u'暂停交易'),  # 平台客服介入处理交易
                              ('refund', u'申请退款'),  # 包车服务完成，用户点击申请退款状态
                              ('refund error', u'退款失败'),  # 退款失败，人工干预
                              ('done', u'交易完成'),  # 交易完成
                              ('close', u'已关闭')], string=u'状态')
    can_refund = fields.Boolean(string=u'可以退款', compute='_compute_can_refund')
    order_amount = fields.Monetary(string=u'订单总额', required=True, readonly=True)
    refund_amount = fields.Monetary(string=u'退款总额', readonly=True)
    service_charge = fields.Float(string=u'劳务费', readonly=True)
    charge_refund = fields.Boolean(string=u'是否退劳务费', readlony=True)
    order_days = fields.Integer(string=u'天数')
    start_date = fields.Date(string=u'开始日期', required=True)
    end_date = fields.Date(string=u'结束日期', required=True)

    @api.depends('state')
    def _compute_can_refund(self):
        for order in self:
            if order.state == 'paid':
                return True
            else:
                return False

    @property
    def partner_mobile(self):
        if self.partner_id.mobile:
            if self.state in ('paid', 'stop', 'refund', 'refund error', 'done'):
                return self.partner_id.mobile
            else:
                middle = self.partner_id.mobile[3:7]
                return self.partner_id.mobile.replace(middle, '****')
        else:
            return u'未知'

    def create_order(self, partner_id, owner_id, owner_product_id, start_date, end_date, note):
        tour_date = datetime.strptime(start_date, "%Y-%m-%d")

        year1 = int(start_date.split('-')[0])
        month1 = int(start_date.split('-')[1])
        day1 = int(start_date.split('-')[2])

        year2 = int(end_date.split('-')[0])
        month2 = int(end_date.split('-')[1])
        day2 = int(end_date.split('-')[2])
        # 租车天数，包括开始日期和结束日期
        order_days = utils.daysBetweenDates(year1, month1, day1, year2, month2, day2) + 1

        # 组装订单
        owner_product = self.env['tour.owner.product'].browse(owner_product_id)
        price = owner_product.price
        order_line = []

        # 如果车主设置了特殊价格，则取特殊价格
        lst_special_price = self.env['tour.product.price'].search_read(
            [('owner_product_id', '=', owner_product.id),
             ('start_date', '<=', start_date),
             ('end_date', '>=', start_date),
             ('active', '=', True)], ['special_price'], limit=1)
        if lst_special_price:
            price = lst_special_price[0]['special_price']
        # 旅游第一天
        order_line.append((0, 0, {'product_id': owner_product.product_id.id, 'name': owner_product.product_id.name,
                                  'owner_product_id': owner_product_id, 'price': price, 'travel_date': start_date}))

        index = 1
        while index < order_days:
            next_date = datetime.strftime(tour_date + timedelta(days=index), "%Y-%m-%d")
            lst_special_price = self.env['tour.product.price'].search_read(
                [('owner_product_id', '=', owner_product.id),
                 ('start_date', '<=', next_date),
                 ('end_date', '>=', next_date),
                 ('active', '=', True)], ['special_price'], limit=1)
            if lst_special_price:
                price = lst_special_price[0]['special_price']
            # 旅游其他天
            order_line.append(
                (0, 0, {'product_id': owner_product.product_id.id, 'name': owner_product.product_id.name,
                        'owner_product_id': owner_product_id, 'price': price,
                        'travel_date': next_date}))
            index += 1

        # 计算订单总额
        order_amount = 0
        for x in order_line:
            order_amount += x[2]['price']

        # 获取系统定义的劳务费
        config = self.env['tour.config.settings']
        service_charge = config.get_config('service_charge', self.create_uid.id)

        order_vals = {
            'company_id': 1,
            'team_id': 1,
            'user_id': 1,
            'date_order': fields.Date.today(),  # 下单日期
            'partner_id': partner_id,
            'owner_id': owner_id,
            'start_date': start_date,
            'end_date': end_date,
            'order_amount': order_amount,  # 订单总额
            'order_line': order_line,
            'service_charge': service_charge,
            'charge_refund': owner_product.charge_refund,  # 查询车主设置的该线路是否退劳务费
            'note': note
        }

        order = self.create(order_vals)
        return order.id

    @api.multi
    def action_batch_to_stop(self):
        for order in self:
            if order.state == 'paid':
                order.state = 'stop'
            else:
                raise ValidationError(_(u'当前状态不是已支付状态，不能暂停！'))

    @api.multi
    def action_batch_recover(self):
        for order in self:
            if order.state == 'stop':
                order.state = 'paid'
            else:
                raise ValidationError(_(u'当前状态不是暂停状态，不能恢复！'))

    @api.multi
    def action_batch_to_close(self):
        for order in self:
            order.state = 'close'

    @api.multi
    def action_batch_to_done(self):
        for order in self:
            order.state = 'done'


class TourSaleOrderLine(models.Model):
    """订单每日明细"""
    _inherit = 'sale.order.line'
    _description = u'继承订单明细'

    owner_product_id = fields.Many2one('tour.owner.product', string=u"车辆线路")
    product_id = fields.Many2one('tour.travel.product', string=u"线路")
    price = fields.Monetary(string=u'单价', readonly=True)
    travel_date = fields.Date(string=u'日期')
